package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.common.util.LocalDateUtil;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.*;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantBaseInfoMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 82 期待  回调
 */
@Service
public class QiDaiPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Resource
    MerchantBaseInfoMapper merchantBaseInfoMapper;
    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        String mobileMd5 = memberSourceInfo.getMobileMd5();
        Map<String, Object> bizmap = new HashMap<>();
        bizmap.put("encryptMobile",mobileMd5);
        bizmap.put("age",memberSourceInfo.getAge());
        bizmap.put("sex", QiDaiUtil.getsex(memberSourceInfo.getSex()));
        bizmap.put("province",memberSourceInfo.getProvince());
        bizmap.put("city",memberSourceInfo.getCity());
        bizmap.put("cnName",memberSourceInfo.getRealname());
        bizmap.put("system",1);
        bizmap.put("ip",memberSourceInfo.getReqIp());
        bizmap.put("amount", QiDaiUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizmap.put("loanAmount", 4);
        bizmap.put("loanFor", QiDaiUtil.getYongtu(memberSourceInfo.getYongtu()));
        bizmap.put("education",QiDaiUtil.getxueli(memberSourceInfo.getXueli()));
        bizmap.put("jobMaster",0);
//        bizmap.put("jobMasterTax",1);
        bizmap.put("jobCard",3);
        bizmap.put("shebao",QiDaiUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        Integer shebaoAmount = RandomUtil.randomInt(300, 501);
        bizmap.put("shebaoAmount",QiDaiUtil.getshebaoAmount(memberSourceInfo.getShebao(),shebaoAmount));
        bizmap.put("gongjijin",QiDaiUtil.getGjj(memberSourceInfo.getGjj()));
        bizmap.put("gongjijinAmount",QiDaiUtil.getGjjAmount(memberSourceInfo.getGjj(),shebaoAmount));
        bizmap.put("house",QiDaiUtil.getHouse(memberSourceInfo.getHouse()));
//        bizmap.put("houseValue",3);
//        bizmap.put("housePledge",1);
        bizmap.put("vehicle",QiDaiUtil.getCar(memberSourceInfo.getCar()));
//        bizmap.put("vehicleYear",1);
//        bizmap.put("vehicleType",1);
//        bizmap.put("vehicleValue",2);
//        bizmap.put("vehiclePledge",1);
        bizmap.put("insurance",QiDaiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizmap.put("zhima",QiDaiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizmap.put("overdue",QiDaiUtil.getyuqi(memberSourceInfo.getYuqi()));


        String publicKey = pushApiKeyParam.getPubKey();
        String aesKey = QiDaiAesUtil.getKey();
        String jsonParam = JSON.toJSONString(bizmap);
        String miAesKey = QiDaiRsaUtil.encryptByPublicKey(aesKey, publicKey);
        String bizData = QiDaiAesUtil.encrypt(jsonParam, aesKey);


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelCode",pushApiKeyParam.getApiCode());
        paramMap.put("miAesKey", miAesKey);
        paramMap.put("bizData",bizData);

        log.info("【期贷】撞库开始【queryUrl】{}【bizParam】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizmap),JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【期待】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizmap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<String, Object> bizmap = new HashMap<>();
        bizmap.put("mobilePhone",memberSourceInfo.getMobile());
        bizmap.put("idNumber",memberSourceInfo.getIdcard());
        bizmap.put("age",memberSourceInfo.getAge());
        bizmap.put("sex", QiDaiUtil.getsex(memberSourceInfo.getSex()));
        bizmap.put("province",memberSourceInfo.getProvince());
        bizmap.put("city",memberSourceInfo.getCity());
        bizmap.put("cnName",memberSourceInfo.getRealname());
        bizmap.put("system",1);
        bizmap.put("ip",memberSourceInfo.getReqIp());
        bizmap.put("amount", QiDaiUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizmap.put("loanAmount", 4);
        bizmap.put("loanFor", QiDaiUtil.getYongtu(memberSourceInfo.getYongtu()));
        bizmap.put("education",QiDaiUtil.getxueli(memberSourceInfo.getXueli()));
        bizmap.put("jobMaster",0);
//        bizmap.put("jobMasterTax",1);
        bizmap.put("jobCard",3);
        bizmap.put("shebao",QiDaiUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        Integer shebaoAmount = RandomUtil.randomInt(300, 501);
        bizmap.put("shebaoAmount",QiDaiUtil.getshebaoAmount(memberSourceInfo.getShebao(),shebaoAmount));
        bizmap.put("gongjijin",QiDaiUtil.getGjj(memberSourceInfo.getGjj()));
        bizmap.put("gongjijinAmount",QiDaiUtil.getGjjAmount(memberSourceInfo.getGjj(),shebaoAmount));
        bizmap.put("house",QiDaiUtil.getHouse(memberSourceInfo.getHouse()));
//        bizmap.put("houseValue",3);
//        bizmap.put("housePledge",1);
        bizmap.put("vehicle",QiDaiUtil.getCar(memberSourceInfo.getCar()));
//        bizmap.put("vehicleYear",1);
//        bizmap.put("vehicleType",1);
//        bizmap.put("vehicleValue",2);
//        bizmap.put("vehiclePledge",1);
        bizmap.put("insurance",QiDaiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizmap.put("zhima",QiDaiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizmap.put("overdue",QiDaiUtil.getyuqi(memberSourceInfo.getYuqi()));

        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String jumpUrl = StrUtil.format("{}prodList", appInfoByAppCode.getH5Url(), memberSourceInfo.getChannelCode());

        bizmap.put("redirectUrl", jumpUrl);

        String publicKey = pushApiKeyParam.getPubKey();
        String aesKey = QiDaiAesUtil.getKey();

        String jsonParam = JSON.toJSONString(bizmap);

        String miAesKey = QiDaiRsaUtil.encryptByPublicKey(aesKey, publicKey);

        String bizData = QiDaiAesUtil.encrypt(jsonParam, aesKey);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelCode",pushApiKeyParam.getApiCode());
        paramMap.put("miAesKey", miAesKey);
        paramMap.put("bizData",bizData);

        log.info("【期贷】导单开始【queryUrl】{}【bizParam】{}【paramMap】{}", requestUrl,  JSON.toJSONString(bizmap),JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【期贷】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizmap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            String data = resultObject.getString("data");

            pushApiResult.setApproveUrl(data);
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(false);
            pushApiResult.setOutOrderNo(memberSourceInfo.getMobileMd5());
            pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        JSONObject jsonObject = JSON.parseObject(paramContent);
        String bizData = jsonObject.getString("bizData");
        String miAesKey = jsonObject.getString("miAesKey");

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoMapper.selectById(infoId);
        String aesKey  = SecureUtil.rsa(merchantBaseInfo.getApiPriKey(), null).decryptStr(miAesKey, KeyType.PrivateKey);
        String result = SecureUtil.aes(aesKey.getBytes()).decryptStr(bizData);

        JSONObject paramObject = JSON.parseObject(result);

        JSONArray phoneList = paramObject.getJSONArray("phoneList");
        String phoneMd5 = phoneList.getString(0);

        noticeParamDTO.setOutOrderNo(phoneMd5);
        noticeParamDTO.setOutFlag(true);

        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(phoneMd5));
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "成功");
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {

        ProtocolParamResult paramResult = new ProtocolParamResult();

        paramResult.setFilePath("/priprotocol/qidai");

        JSONObject userInfo = new JSONObject();
        userInfo.put("username", memberSourceInfo.getRealname());
        userInfo.put("mobile", memberSourceInfo.getMobile());
        userInfo.put("datetime", LocalDateUtil.getNowDateStr(LocalDateUtil.TOTAL_DATE_TIME));
        userInfo.put("uid", String.valueOf(memberSourceInfo.getUid()));

        paramResult.setUserInfo(userInfo);

        return paramResult;
    }
}
